<template>
  <div class="pannel-account">
    <el-form
      :model="account"
      :rules="accountRules"
      :label-width="80"
      size="large"
      status-icon
      ref="formRef"
    >
      <el-form-item label="手机号">
        <el-input />
      </el-form-item>
      <el-form-item label="验证码">
        <div class="verify-code">
          <el-input />
          <el-button class="get-btn" type="primary">获取验证码</el-button>
        </div>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model.trim="account.password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="password">
        <el-input v-model.trim="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import useLoginStore from "@/store/login/login";
import type { FormRules } from "element-plus";
import { ElForm, ElMessage } from "element-plus";
import type { IAccount } from "@/types";
import { localCache } from "@/utils/cache";

const CACHE_NAME = "name";
const CACHE_PASSWORD = "password";
const formRef = ref<InstanceType<typeof ElForm>>();
const loginStore = useLoginStore();
//图形验证码
let identifyCodes = "1234567890";
let identifyCode = ref("3212");

const account = reactive<IAccount>({
  name: localCache.getCache(CACHE_NAME) ?? "",
  password: localCache.getCache(CACHE_PASSWORD) ?? "",
});

const accountRules: FormRules = {
  name: [
    { required: true, message: "必须输入帐号信息~", trigger: "blur" },
    {
      pattern: /[a-z0-9]{6,20}/,
      message: "必须是6~20位数字或字母组成~",
      trigger: "change",
    },
  ],
  password: [
    { required: true, message: "必须输入密码信息~", trigger: "blur" },
    {
      pattern: /^[a-z0-9]{3,}$/,
      message: "必须是3位以上的数字或字母组成~",
      trigger: "change",
    },
  ],
};

onMounted(() => {
  identifyCode.value = "";
  makeCode(identifyCodes, 4);
});

const randomNum = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min);
};

const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)];
  }
};

const loginAction = (isRemPwd: boolean) => {
  formRef.value?.validate((valid) => {
    if (valid) {
      loginStore.loginAccountAction(account).then(() => {
        if (isRemPwd) {
          localCache.setCache(CACHE_NAME, account.name);
          localCache.setCache(CACHE_PASSWORD, account.password);
        } else {
          localCache.removeCache(CACHE_NAME);
          localCache.removeCache(CACHE_PASSWORD);
        }
      });
    }
  });
};

defineExpose({
  loginAction,
});
</script>

<style lang="less" scoped>
.pannel-account {
  color: red;
}

.login_code {
  height: 38px;
}

.test-account {
  font-size: 12px;
  color: #000;
}

:deep(.el-input-group__append) {
  padding: 0;
  overflow: hidden;
}

.verify-code {
  display: flex;
  width: 100%;

  .get-btn {
    margin-left: 8px;
  }
}
</style>
